import { Component, Inject} from '@angular/core';
import { Router } from '@angular/router';
import { StartupService } from '@core';
import { DA_SERVICE_TOKEN, ITokenService } from '@delon/auth';
import { _HttpClient } from '@delon/theme';
import { environment } from '@env/environment';

@Component({
  selector: 'app-passport-login',
  templateUrl: 'login.component.html'
})
export class UserLoginComponent{
  constructor(
    private router: Router,
    @Inject(DA_SERVICE_TOKEN) private tokenService: ITokenService,
    private startupSrv: StartupService,
    public http: _HttpClient,
  ) {}
  username: string;
  password: string;

  submit(): void {

    this.http
    .post(
      `${environment.sys.ctx}/oauth/token?_allow_anonymous=true`,
      {
        username: this.username,
        password: this.password,
        //captcha_token: this.captcha.value,
        grant_type: 'password',
      },
      {
        username: this.username,
        password: this.password,
        //captcha_token: this.captchaToken,
        //captcha: this.captcha.value,
        grant_type: 'password',
      },
      { headers: { Authorization: 'Basic Z2VuZXJpYzoxMjM=', 'Content-Type': 'application/x-www-form-urlencoded' } },
    )
    .subscribe((res) => {
      if (res.success && !res.success) {
        return;
      }
      // 设置用户Token信息
      this.tokenService.set({ token: res.access_token });
      // 重新获取 StartupService 内容，我们始终认为应用信息一般都会受当前用户授权范围而影响
      this.startupSrv.load().then(() => {
        let url = this.tokenService.referrer!.url || '/';
        if (url.includes('/passport')) {
          url = '/';
        }
        this.router.navigateByUrl(url);
      });
    });
  }
}
